package com.solotiger.douban.factory.gson;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.solotiger.douban.biz.model.BaseResult;
import com.solotiger.douban.exception.ResultException;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final Gson gson;
    private final Type type;

    GsonResponseBodyConverter(Gson gson, Type type) {
        this.gson = gson;
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            String response = value.string();
            //当去请求错误时,会有错误信息
            BaseResult baseResult = gson.fromJson(response, BaseResult.class);
            if (!TextUtils.isEmpty(baseResult.getMsg())) {
                throw new ResultException(baseResult.getCode(), baseResult.getMsg());
            } else {
                return gson.fromJson(response, type);
            }
        } finally {
            value.close();
        }
    }
}
